package SortAlgorithm;

import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Classname QuickSort 快排
 * @Description TODO 对冒泡的改进；
 * @Date 2021/11/10 16:30
 * @Created K024851
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] arr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr[i] = (int) (Math.random() * 8000000);
        }
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        System.out.println("排序前：" + format);
        quickSort(arr, 0, arr.length - 1);
        Date date2 = new Date();
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format2 = simpleDateFormat2.format(date2);
        System.out.println("排序后：" + format2);
    }

    public static void quickSort(int[] arr, int left, int right) {
        int l = left;//坐下标
        int r = right;//又下标
        //中轴
        int pivot = arr[(left + right) / 2];
        int temp = 0;
        while (l < pivot) {
            while (arr[l] < pivot) {
                l += 1;
            }
            while (arr[r] > pivot) {
                r -= 1;
            }
            if (l >= r) {
                break;
            }

            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;

            if (arr[l] == pivot) {
                r -= 1;
            }

            if (arr[r] == pivot) {
                l += 1;
            }


        }
        if (l == r) {
            l += 1;
            r -= 1;
        }


        if (left<r){
            quickSort(arr, left, r);
        }
        if (right>l){
            quickSort(arr, l, right);
        }
    }
}
